package com.lkm.app_ui.ui.fj.img;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.TaskHelp;
import com.lkm.app_ui.log.AppLogger;
import com.lkm.comlib.help.FileUploadNew;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.frame.file.FileHelper;
import com.lkm.frame.task.ProgressData;
import com.lkm.frame.task.ProgressUpAble;
import com.lkm.frame.task.StopAble;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.javatool.lang.NameValueP;
import com.lkm.market2_0.entity.ResponEntity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;



class UpImageTask extends TaskAdapter {



    public static void tryUp() {
        Task task = TaskHelp.getTask(UpImageTask.class.getName());
        if (task != null && task.getIsContinue()) {
            return;
        }
        TaskHelp.cancelById(UpImageTask.class.getName());

        UpImageTask upImageTask = new UpImageTask();
        upImageTask.action();
        upImageTask.execTask();
    }

    private UpImageTask() {
        super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), UpImageTask.class.getName(), AppConst.getTaskManager2());
    }


    @Override
    public void doExecuting(Object param) {
        super.doExecuting(param);

        mTaskExecutor.executor(new Runnable() {
            @Override
            public void run() {
                try {
                    while (getIsContinue()) {
                        try {
                            up();
                        }
                        catch (Throwable e){}

                        try {
                            Thread.sleep(4 * 1000);
                        }catch (Exception e){

                        }
                    }
                } catch (Exception e) {
                    cancel();
                }
            }
        });
    }

    private void up() {
        File[] files = ImgFiler.getUpFiles();

        if (!CollectionHelp.isEmpty(files)) {

            List<File> ups = new ArrayList<>();
            long allSize = 0;
            for (File f : files) {

//                System.out.println("==== 名字"+f.getName());

                if (StringHelp.length(f.getName()) < 20 || StringHelp.isEmpty(FileHelper.getExtension(f.getName()))) {

                    try {
                        f.delete();
                    }catch (Exception e){}
                    continue;
                }


                allSize += f.length();
                ups.add(f);



                if (allSize > upSize * (1024 * 1024)) {
                    break;
                }

            }
            if(!getIsContinue())return ;


            if (RunTimeData.steelyardInfo.upDataApiTo == null || StringHelp.isEmpty(RunTimeData.steelyardInfo.upDataApiTo.fjUpImgUrl)) {
                deletes(ups);
            }

            ResponEntity<Result> re = upOrderImage(AppConst.getApplication(), ups.toArray(new File[ups.size()]), UpImageTask.this, null);
            if (re.isSuccess()) {
                deletes(re.getData().success);
                deletes(re.getData().discard);
            }else {

                upSize = Math.max(upSize - 0.1f, 0);
            }
        } else {
            complete(null);
        }
    }
    private float upSize = 0.4f;
    private void deletes(String[] success) {
        if (!CollectionHelp.isEmpty(success)) {
            for (String s : success) {
                FileHelper.deleteFolder(new File(AppConfig.DataFile.getFjImgUpFilePath(s)));
            }
        }
    }
    private void deletes(List<File> files) {
        if (!CollectionHelp.isEmpty(files)) {
            for (File s : files) {
                FileHelper.deleteFolder(s);
            }
        }
    }

    private class Result {


        @SerializedName("success")
        public String[] success;
        @SerializedName("error")
        public String[] error;

        @SerializedName("discard")
        public String[] discard;

    }

    public static ResponEntity<Result> upOrderImage(Context context, File[] files, StopAble sa, ProgressUpAble<ProgressData<String>> pua) {
        NameValueP[] uploadFiles_ = new NameValueP[files.length];
        for (int i = 0; i < uploadFiles_.length; i++) {
            uploadFiles_[i] = new NameValueP(files[i].getName(), files[i].getAbsolutePath());
        }
        if(AppLogger.Order.isDebug())
        AppLogger.Order.temp("==== " + new Gson().toJson(uploadFiles_));

//        RunTimeData.steelyardInfo.upDataApiTo.fjUpImgUrl ="http://zhongzi.web.ic1986.com/api/tc.ashx?act=server_set_file";
        String resule = FileUploadNew.uploadFile(context, RunTimeData.steelyardInfo.upDataApiTo == null ? "" : RunTimeData.steelyardInfo.upDataApiTo.fjUpImgUrl, new NameValueP[]{
                new NameValueP("ukey", RunTimeData.steelyardInfo.getSteelyardMac()),
                new NameValueP("b_id", RunTimeData.steelyardInfo.getB_id()),

                new NameValueP("oid", "" + RunTimeData.steelyardInfo.getOrg()),


        }, uploadFiles_, null, null, "image/jpeg",false, sa, pua);
        System.out.println("==== "+resule);

        if(resule == null){

            try {
                Thread.sleep(5 * 1000);
            }catch (Exception e){}
        }
        return ResponEntity.fromJson(resule,
                Result.class, "");
    }

}
